<template>
  <div class="login-container">
    <div class="login-form">
      <div class="title">
        <h2>商城在线客服系统</h2>
        <p>请登录您的账号</p>
      </div>
      
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form-content"
        auto-complete="on"
        label-position="left"
      >
        <el-form-item prop="username">
          <span class="svg-container">
            <i class="el-icon-user"></i>
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="用户名"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>

        <el-form-item prop="password">
          <span class="svg-container">
            <i class="el-icon-lock"></i>
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <i :class="passwordType === 'password' ? 'el-icon-view' : 'el-icon-hide'"></i>
          </span>
        </el-form-item>

        <el-button
          :loading="loading"
          type="primary"
          style="width:100%;margin-bottom:30px;"
          @click.native.prevent="handleLogin"
        >
          登录
        </el-button>

        <div class="tips">
          <p>默认账号：</p>
          <p>管理员：admin / 123456</p>
          <p>客服：service / 123456</p>
          <p>用户：user / 123456</p>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/auth'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      errorMessage: '' // 添加错误消息字段
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    async handleLogin() {
      // 重置错误消息
      this.errorMessage = ''
      
      try {
        // 验证表单
        const valid = await this.$refs.loginForm.validate()
        if (!valid) {
          console.log('表单验证失败')
          return false
        }
        
        this.loading = true
        
        // 调用登录API
        const response = await login(this.loginForm)
        
        // 检查响应是否包含必要的数据
        if (!response.data || !response.data.token) {
          throw new Error('登录响应缺少必要数据')
        }
        
        // 保存认证信息到Vuex
        await this.$store.dispatch('login', {
          token: response.data.token,
          userType: response.data.userType,
          user: response.data.user
        })
        
        // 重定向到目标页面或默认页面
        const redirectPath = this.redirect || '/chat'
        this.$router.push(redirectPath)
      } catch (error) {
        console.error('登录失败:', error)
        
        // 根据错误类型显示不同的错误消息
        if (error.response && error.response.status === 401) {
          this.errorMessage = '用户名或密码错误'
        } else if (error.message === '登录响应缺少必要数据') {
          this.errorMessage = '服务器响应异常，请稍后重试'
        } else if (error.response && error.response.data && error.response.data.message) {
          this.errorMessage = error.response.data.message
        } else {
          this.errorMessage = '登录失败，请检查网络连接后重试'
        }
        
        // 显示错误提示
        this.$message.error(this.errorMessage)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;

  .login-form {
    width: 400px;
    max-width: 100%;
    padding: 40px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);

    .title {
      text-align: center;
      margin-bottom: 30px;

      h2 {
        color: #333;
        margin: 0 0 10px 0;
        font-size: 24px;
      }

      p {
        color: #666;
        margin: 0;
        font-size: 14px;
      }
    }

    .login-form-content {
      .el-form-item {
        position: relative;
        margin-bottom: 20px;

        .svg-container {
          position: absolute;
          left: 10px;
          top: 50%;
          transform: translateY(-50%);
          color: #889aa4;
          z-index: 10;
        }

        .el-input {
          input {
            padding-left: 40px;
            height: 45px;
            border: 1px solid #dcdfe6;
            border-radius: 5px;
            font-size: 14px;

            &:focus {
              border-color: #409eff;
            }
          }
        }

        .show-pwd {
          position: absolute;
          right: 10px;
          top: 50%;
          transform: translateY(-50%);
          color: #889aa4;
          cursor: pointer;
          user-select: none;
        }
      }

      .el-button {
        height: 45px;
        font-size: 16px;
        border-radius: 5px;
      }
    }

    .tips {
      text-align: center;
      color: #666;
      font-size: 12px;
      line-height: 1.5;

      p {
        margin: 5px 0;
      }
    }
  }
}
</style>
